package com.xzgj.fmmall.service.impl;

import com.xzgj.fmmall.dao.UserMapper;
import com.xzgj.fmmall.entity.User;
import com.xzgj.fmmall.service.UserService;
import com.xzgj.fmmall.service.exception.UserNameDuplicatedException;
import com.xzgj.fmmall.vo.ResStatus;
import com.xzgj.fmmall.vo.ResultVO;
import com.xzgj.fmmall.vo.UserVO;
import com.xzgj.fmmall.vo.utils.JWTUtil;
import com.xzgj.fmmall.vo.utils.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Transactional
    /**
     * 多个用户注册，并发情况 ；要用事务管理
     */
    public ResultVO userRegister(String name, String password) {

        if (name.length() == 0 || password.length() == 0){
            return new ResultVO(ResStatus.NO,ResStatus.UserNameOrPasswordIsNotExist,null);
        }
        //根据账号查询用户是否被注册
        UserVO user = userMapper.queryUserByName(name);

        /**
         * 根据时间戳生成唯一id
         */
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
//        String user_id = sdf.format(System.currentTimeMillis());
//        System.out.println("user_id:"+user_id);
        //id:202010221400070793

        if (user == null){
//对输入的密码pwd进行加密
//            使用加密后的密码和用户user中的密码进行匹配
//            补全数据
            String md5Pwd = MD5.getMD5(password);
            UserVO newUser = new UserVO();
//            newUser.setUserId(user_id);
            newUser.setUserName(name);
            newUser.setPassword(md5Pwd);
            newUser.setUserImg("https://s2.loli.net/2021/12/09/By8ANevSV4L5CTt.jpg");
            newUser.setUserRegtime(new Date());
            newUser.setUserModtime(new Date());
            int i = userMapper.insertUser(newUser);

            if (i > 0){
// 验证成功
                return new ResultVO(ResStatus.OK,ResStatus.registerSuccess,newUser);
            }else {
// 密码错误
                return new ResultVO(ResStatus.NO,ResStatus.registerError,null);
            }
        }else {

// 抛出异常
//            throw new UserNameDuplicatedException("用户名被占用");
            return new ResultVO(ResStatus.NO,ResStatus.userIsExist,null);

        }

    }

    @Override
    public ResultVO queryUsers(){
        List<User> users = userMapper.queryUsers();
        if (users.size() > 0){
            return new ResultVO(ResStatus.OK,ResStatus.operationSuccess,users);
        }else {
            return new ResultVO(ResStatus.NO,ResStatus.FAILURE,null);
        }

    }


    @Override
    public ResultVO checkLogin(String name, String password) {
//根据账号查询用户信息
        UserVO user = userMapper.queryUserByName(name);
        if (user == null){
// 用户不存在
            return new ResultVO(ResStatus.OK,ResStatus.isNotExist,null);
        }else {
//对输入的密码pwd进行加密
//            使用加密后的密码和用户user中的密码进行匹配
            String md5Pwd = MD5.getMD5(password);

            String token = JWTUtil.createToken(user.getUserId()+"");

            if (ObjectUtils.isEmpty(token)) {
                return new ResultVO(ResStatus.NO, ResStatus.loginError,null);
            } else {

                int result = JWTUtil.verifyToken(token);

                if (result != 0) {
                    return new ResultVO(ResStatus.NO, ResStatus.tokenVerifyFailure,null);
                }
            }
            System.out.println("token is:" + token);

            user.setToken(token);
            if (user.getPassword().equals(md5Pwd)){
// 验证成功
                return new ResultVO(ResStatus.OK,ResStatus.loginSuccess,user);
            }else {
// 密码错误
                return new ResultVO(ResStatus.NO,ResStatus.passwordError,null);

            }
        }
    }

    @Override
    public ResultVO checkTokenIsValid(String token) {
//        0 验证成功，1、2、3、4、5 验证失败
        int res = JWTUtil.verifyToken(token);
        if (res == 0){
            return new ResultVO(ResStatus.OK,ResStatus.SUCCESS,null);
        }else {
            return new ResultVO(ResStatus.NO,ResStatus.tokenVerifyFailure,null);
        }
    }

    @Override
    public ResultVO getUserInfoByUserId(String userId) {
        UserVO userVO = userMapper.queryUserInfoByUserId(userId);
        if (userVO == null){
            return new ResultVO(ResStatus.NO,ResStatus.isNotExist,null);
        }else {
            return new ResultVO(ResStatus.OK,ResStatus.SUCCESS,userVO);
        }
    }

    @Override
    public ResultVO updateUserInfoByUserId(User user) {
        if (user.getUserId() == null){
            return new ResultVO(ResStatus.NO,ResStatus.isNotExist,null);
        }
        int result = userMapper.updateUserInfoByUserId(user,user.getUserId());
        if (result > 0){
            return new ResultVO(ResStatus.OK,ResStatus.SUCCESS,user);
        }else {
            return new ResultVO(ResStatus.NO,ResStatus.FAILURE,null);
        }
    }
}
